import FSMBlackboard from "./FSMBlackboard";
import { FSMState } from "./FSMState";

/**
 * 有限状态机
 */
export default class FSM {
    private _statesMap: Record<number, FSMState>;
    /**
     * 当前状态
     */
    public currentState: FSMState;
    /**
     * 上一个状态
     */
    public lastState: FSMState;
    /**
     * 状态机数据
     */
    public data: FSMBlackboard;
    /**
     * 状态id
     */
    private _stateId: number;

    public node: cc.Node;
    
    init(data: FSMBlackboard) {
        this._statesMap = {};
        this._stateId = 0;
        this.data = data;
        this.data.init();
    }

    /**
     * 添加状态
     * @param state 
     * @returns 
     */
    public addState(state: FSMState) {
        state.id = ++this._stateId;
        this._statesMap[state.id] = state;
        state.fsm = this;
        state.init();
        return state;
    }

    /**
     * 切换状态
     * @param id 
     */
    public changeState(id: number) {
        this.lastState = this.currentState;
        this.currentState?.onEixt();
        this.currentState = this._statesMap[id];
        this.currentState?.onEnter();
    }

    /**
     * 获取状态id
     * @param name 
     * @returns 
     */
    public getStateId(name: string) {
        for (let key in this._statesMap) {
            if (this._statesMap[key].name === name) {
                return this._statesMap[key];
            }
        }
        return -1;
    }

    public getState(id: number) {
        return this._statesMap[id];
    }

    public update(dt) {
        if (!this.currentState) {
            this.changeState(1);
        } else {
            let toId = this.currentState.tick();
            if (toId !== -1) {
                this.changeState(toId);
            }
        }
        this.currentState?.update(dt);
    }

    public exit() {
        this.lastState = null;
        this.currentState?.onEixt();
        this.currentState = null;
    }
}